using MauiBuilder.ViewModels;

namespace MauiBuilder.Views;

public partial class ChatPage : ContentPage
{
    private ChatViewModel _viewModel;

    public ChatPage(ChatViewModel viewModel)
    {
        InitializeComponent();
        BindingContext = _viewModel = viewModel;
        
        // 监听消息集合变化，自动滚动到底部
        _viewModel.Messages.CollectionChanged += OnMessagesCollectionChanged;
    }

    private async void OnMessagesCollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
        {
            // 延迟一点时间确保UI更新完成
            await Task.Delay(100);
            
            // 滚动到最新消息
            if (_viewModel.Messages.Count > 0)
            {
                var lastMessage = _viewModel.Messages.Last();
                MessagesCollectionView.ScrollTo(lastMessage, position: ScrollToPosition.End, animate: true);
            }
        }
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();
        
        // 页面出现时聚焦到输入框
        MessageEntry.Focus();
        
        // 滚动到底部
        if (_viewModel.Messages.Count > 0)
        {
            var lastMessage = _viewModel.Messages.Last();
            MessagesCollectionView.ScrollTo(lastMessage, position: ScrollToPosition.End, animate: false);
        }
    }

    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        
        // 页面消失时取消输入框焦点
        MessageEntry.Unfocus();
    }
}